import { createGroup, type SiteGroup, updateGroup } from '@/api/SiteGroupApi.ts'
import { useSiteGroupStore } from '@/config/store/UseSiteGroupStore.ts'
import { type ArcoForm, type ArcoFormRules, ArcoFormTool } from '@/tool/ArcoFormTool.ts'
import { GeneralModelService } from '@/tool/GeneralModelService.ts'
import { useGlobalProperties } from '@/tool/UseGlobalProperties.ts'
import { ObjectTool } from '@es-tool/core'
import { type ComponentCustomProperties, ref, type Ref, watch } from 'vue'


export type PropsType = {
    isAdd?: boolean,
    group?: object
}

export class SiteGroupFormModalService extends GeneralModelService {

    public readonly props: PropsType

    public readonly formRef: Ref<ArcoForm | null>

    public readonly formIsLoading: Ref<boolean> = ref(false)

    public readonly formData: Ref<Partial<SiteGroup>> = ref<Partial<SiteGroup>>({})

    public readonly siteGroupStore: ReturnType<typeof useSiteGroupStore>

    public readonly formRule: ArcoFormRules<SiteGroup> = {
        name: [ { type: 'string', required: true, message: '', maxLength: 200 } ],
    }

    public readonly globalProperties: ComponentCustomProperties


    constructor(props: PropsType, formRef: Ref<ArcoForm | null>) {
        super()
        this.props = props
        this.formRef = formRef
        this.siteGroupStore = useSiteGroupStore()

        this.globalProperties = useGlobalProperties()!

        this.formData.value = this.newDefaultSite()

        watch(() => props.group, () => {
            if (this.props.group) {
                const group = ObjectTool.copy(this.props.group)
                this.formData.value = group ?? this.newDefaultSite()
            }
        }, { immediate: true })

        this.formSubmit = this.formSubmit.bind(this)
    }

    public async formSubmit(): Promise<boolean> {
        try {
            this.formData.value.sort = this.siteGroupStore.groupList.length

            this.formIsLoading.value = true
            await ArcoFormTool.validate(this.formRef)
            await (this.props.isAdd
                    ? createGroup(this.formData.value as any)
                    : updateGroup(this.formData.value as any))
            if (this.props.isAdd) {
                this.formData.value = this.newDefaultSite()
            }
            this.globalProperties.$application.siteGroupService.initGroupList()
            return true
        } catch (e) {
            console.debug(e)
            return false
        } finally {
            this.formIsLoading.value = false
        }
    }

    private newDefaultSite(): Partial<SiteGroup> {
        return {
            id: null,
            icon: '',
            name: '新分组',
            sort: 9999,
            description: '',
        }
    }

}
